package com.sinoatma.physignsmonitor.fragment

import android.annotation.SuppressLint
import android.util.Log
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.clj.fastble.BleManager
import com.clj.fastble.callback.BleScanCallback
import com.clj.fastble.data.BleDevice
import com.clj.fastble.scan.BleScanRuleConfig
import com.coder.vincent.series.common_lib.application
import com.common.frame.base.BaseFragment
import com.common.frame.extension.setSingleClick
import com.jeremyliao.liveeventbus.LiveEventBus
import com.sinoatma.physignsmonitor.MyApp
import com.sinoatma.physignsmonitor.constant.*
import com.sinoatma.physignsmonitor.R
import com.sinoatma.physignsmonitor.adapter.DevicesBleAdapter
import com.sinoatma.physignsmonitor.bean.BleDevicePower
import com.sinoatma.physignsmonitor.databinding.FragmentDeviceManagementBinding
import com.sinoatma.physignsmonitor.view.LoadProgressDialog

/**
 * 设备管理
 */
@SuppressLint("MissingPermission")
class DeviceManagementFragment : BaseFragment<DeviceManagementViewModel,FragmentDeviceManagementBinding>() {
    override fun layoutId(): Int =R.layout.fragment_device_management
    lateinit var loadProgressDialog: LoadProgressDialog
    lateinit var bleManager: BleManager
    var deviceList = mutableListOf<BleDevice>()
    lateinit var adapter: DevicesBleAdapter
    var type=0


    override fun initData() {
        loadProgressDialog = LoadProgressDialog(requireActivity())
        bleManager = BleManager.getInstance().apply {
            init(application)
            enableBluetooth()
            initScanRule(BleScanRuleConfig.Builder().build())
        }
    }

    override fun initView() {
        adapter = DevicesBleAdapter(deviceList)
        binding.bleRecycler.layoutManager= LinearLayoutManager(requireActivity())
        binding.bleRecycler.adapter = adapter
    }


    override fun onResume() {
        super.onResume()
        binding.tvBleNameSpo.text="${O2RingName}"
        binding.tvBleNameTempera.text="${TempName}"
        binding.tvBleNameBp.text="${BPName}"

        binding.tvBleNameSpoRight.text="${O2RingNameRight}"
        binding.tvBleNameTemperaRight.text="${TempNameRight}"
        binding.tvBleNameBpRight.text="${BPNameRight}"
        if (BloodTransfusionModeFlag==0){
          binding.reBloodTransBp.visibility=View.GONE
          binding.reBloodTransSpo.visibility=View.GONE
          binding.reBloodTransTemp1.visibility=View.GONE
          binding.tvName1.text="血氧设备"
          binding.tvName2.text="血压设备"
          binding.tvName3.text="体温设备"
        }else{
            binding.tvName1.text="左侧血氧设备"
            binding.tvName2.text="左侧血压设备"
            binding.tvName3.text="左侧体温设备"
            binding.layoutBloodTransTemp.visibility=View.GONE
        }

    }



    override fun initListener() {
        super.initListener()
        adapter.setOnItemClickListener { _, _, position ->
            if (deviceList.size==0){
                return@setOnItemClickListener
            }
            when( viewModel.scanBleName)
            {
               "O2Ring"->{
                   if (type==0){
                       binding.tvBleNameSpo.text="${deviceList[position].device.name}"
                       O2RingName=deviceList[position].device.name
                       O2RingMac=deviceList[position].device.address
                   }else{
                       binding.tvBleNameSpoRight.text="${deviceList[position].device.name}"
                       O2RingNameRight=deviceList[position].device.name
                       O2RingMacRight=deviceList[position].device.address
                   }

                   Log.e("zsy","${deviceList[position].device.name}  ${deviceList[position].device.address}")
                   deviceList.clear()
               }
                "RE-TMP"->{
                    if (type==0){
                        binding.tvBleNameTempera.text="${deviceList[position].device.name}"
                        TempName=deviceList[position].device.name
                        TempMac=deviceList[position].device.address
                    }else{
                        binding.tvBleNameTemperaRight.text="${deviceList[position].device.name}"
                        TempNameRight=deviceList[position].device.name
                        TempMacRight=deviceList[position].device.address
                    }

                    Log.e("zsy","${deviceList[position].device.name}  ${deviceList[position].device.address}")
                    deviceList.clear()
                }
                "PC"->{
                    if (type==0){
                        binding.tvBleNameBp.text="${deviceList[position].device.name} "
                        BPName=deviceList[position].device.name
                        BPMac=deviceList[position].device.address
                    }else{
                        binding.tvBleNameBpRight.text="${deviceList[position].device.name}"
                        BPNameRight=deviceList[position].device.name
                        BPMacRight=deviceList[position].device.address
                    }

                    Log.e("zsy","${deviceList[position].device.name}  ${deviceList[position].device.address}")
                    deviceList.clear()
                }
            }
        }
        //血氧开始搜索
        binding.tvStartOring.setSingleClick {
            type=0
            deviceList.clear()
            loadProgressDialog.showWithAutoClose("蓝牙搜索...",3)
            viewModel.scanBleName= "O2Ring"
            startScan()
        }
        //血压开始搜索
        binding.tvStartBp.setSingleClick {
            type=0
            deviceList.clear()
            loadProgressDialog.showWithAutoClose("蓝牙搜索...",3)
            viewModel.scanBleName="PC"
            startScan()
        }
        //温度计开始搜索
        binding.tvStartTemp.setSingleClick {
            type=0
            deviceList.clear()
            loadProgressDialog.showWithAutoClose("蓝牙搜索...",3)
            viewModel.scanBleName="RE-TMP"
            startScan()
        }

        //血氧开始搜索
        binding.tvStartOringRight.setSingleClick {
            type=1
            deviceList.clear()
            loadProgressDialog.showWithAutoClose("蓝牙搜索...",3)
            viewModel.scanBleName= "O2Ring"
            startScan()
        }
        //血压开始搜索
        binding.tvStartBpRight.setSingleClick {
            type=1
            deviceList.clear()
            loadProgressDialog.showWithAutoClose("蓝牙搜索...",3)
            viewModel.scanBleName="PC"
            startScan()
        }
        //温度计开始搜索
        binding.tvStartTempRight.setSingleClick {
            type=1
            deviceList.clear()
            loadProgressDialog.showWithAutoClose("蓝牙搜索...",3)
            viewModel.scanBleName="RE-TMP"
            startScan()
        }
    }

     fun startScan() {
         if (bleManager.scanSate.code==1){
             bleManager.cancelScan()
         }
        bleManager.scan(object : BleScanCallback() {
            override fun onScanStarted(success: Boolean) {
                loadProgressDialog.dismiss()
            }
            override fun onLeScan(bleDevice: BleDevice) {
            }
            override fun onScanFinished(scanResultList: MutableList<BleDevice>?) {
                loadProgressDialog.dismiss()
            }
            override fun onScanning(bleDevice: BleDevice) {
                // 可以在扫描过程中处理设备信息
                bleDevice.let { device ->
                    if (null!=device.name&& device.name.contains(viewModel.scanBleName) && !deviceList.contains(device)) {
                        Log.e("zsy","${device.name}     ${!deviceList.contains(device)}")
                        // 将新设备添加到列表
                        deviceList.add(bleDevice)
                        adapter.notifyDataSetChanged()
                    }
                }
            }
        })
    }


}